;
layui.define(['element','jquery','layer'], function (exports) {
    let $ = layui.jquery;
    let layer = layui.layer;
    let element = layui.element;

    var DO_LOGIN   = "/login";
    var DO_LOGOUT  = "/logout";
    var LOGIN_PAGE = "/ghdg/login.html";

    var obj = {
        // 接口代码
        responseCode: {
            commonFailure: '9999',
            error: '200',
            success:'100',
            user: {
                verifyError:'1000',//用户权限不足
                loginSuccess:'2000',//登录成功
                logoutSuccess: '3000',//登出成功
                notLogin:'2001',//未登录
                accountExpired:'2002',//账号已过期
                credentialsError:'2003',//凭证错误
                credentialsExpired:'2004',//凭证过期
                accountDisable:'2005',//账号不可用
                accountLocked:'2006',//账号锁定
                accountNotExist:'2007',//账号不存在
                accountExist:'2008',//账号已存在
                accountUseByOthers:'2009',//账号在别处登录
                permissionFailure:'4000',//用户权限不足
            }
        },
        modelCode: {
            operLog: {
                businessType: {
                    OTHER  : 0,
                    INSERT : 1,
                    UPDATE : 2,
                    DELETE : 3,
                    GRANT  : 4,
                    EXPORT : 5,
                    IMPORT : 5,
                    FORCE  : 7,
                    CLEAN  : 8
                },
                operatorType: {
                    OTHER  : 0,
                    MANAGE : 1,
                    MOBILE : 2
                },
                businessStatus: {
                    SUCCESS : 0,
                    FAIL    : 1
                }
            }
        },
        jsonType:{
            ujson:'json',
            json:'json',
            jsonp:'jsonp',
            text:'text'
        },
        // 封装 AJAX 请求
        request: function (options, doSuccess, successDoneCallback, doError, load) {
            var defaults = {
                url:'/',
                type:'post',
                dataType: obj.jsonType.ujson,
                traditional: false,
                successCode: obj.responseCode.success,
                timeout: 30000
            };
            var options = $.extend(defaults, options);
            var loadIndex;
            $.ajax({
                url: options.url,
                type: options.type,
                dataType: options.dataType,
                traditional: options.traditional,
                timeout: options.timeout,
                data: options.where,
                success: function (resp, stat) {
                    if(resp.code == options.successCode) {//成功回调
                        doSuccess(resp,stat)
                        // 回调
                        if(successDoneCallback) {
                            successDoneCallback(resp,stat);
                        }
                    }else{
                        if(doError) {
                            doError(resp)
                        }else{
                            obj.defaultErrorhandler(resp)
                        }
                    }
                },
                error: function () {
                    layer.close(loadIndex);
                    layer.msg("服务器错误", {icon: 2, time: 2000});
                },
                complete:function () {
                    if (load) {
                        layer.close(loadIndex);
                    }
                },
                beforeSend: function () {
                    if (load) {
                        loadIndex = layer.load(0, {shade: 0.3});
                    }
                }
            })
        },
        defaultErrorhandler: function (resp) {
            var c = resp.code;
            if(c == obj.responseCode.user.logoutSuccess) {//登出成功
                top.location.href = LOGIN_PAGE;//'/login.html'
            } else if(c == obj.responseCode.user.permissionFailure){//权限不足
                layer.msg(resp.name)
            } else if(c == obj.responseCode.user.notLogin){//未登录
                layer.msg(resp.name)
                layer.confirm('凭证已过期，是否重新登录？', {
                    btn: ['确认','取消'] //按钮
                }, function(){
                    obj.logout();
                }, function(){});
            } else if(c == obj.responseCode.user.accountExpired){//账号已过期
                layer.msg(resp.code + ":" + resp.name)
            } else if(c == obj.responseCode.user.credentialsError){//凭证错误
                layer.msg(resp.code + ":" + resp.name)
            } else if(c == obj.responseCode.user.credentialsExpired){//凭证过期
                layer.msg(resp.code + ":" + resp.name)
            } else if(c == obj.responseCode.user.accountDisable){//账号不可用
                layer.msg(resp.code + ":" + resp.name)
            } else if(c == obj.responseCode.user.accountLocked){//账号锁定
                layer.msg(resp.code + ":" + resp.name)
            } else if(c == obj.responseCode.user.accountNotExist){//账号不存在
                layer.msg(resp.code + ":" + resp.name)
            } else if(c == obj.responseCode.user.accountExist){//账号已存在
                layer.msg(resp.code + ":" + resp.name)
            } else if(c == obj.responseCode.user.accountUseByOthers){//账号在别处登录
                layer.msg(resp.code + ":" + resp.name)
            } else if(c == obj.responseCode.user.permissionFailure){//用户权限不足
                layer.msg(resp.code + ":" + resp.name)
            } else {
                //$('#error').html(resp.name)
                layer.msg(resp.code + ":" + resp.name)
                layer.confirm('即将进入登录？', {
                    btn: ['确认','取消'] //按钮
                }, function(){
                    obj.logout();
                }, function(){});
            }
        },
        /**
         * 把 权限 的下拉框信息写到缓存中, 以字符串形式。以上是保存和读取操作。
         * 读取时以字符串形式返回, 使用时使用JSON.parse()方式
         * @param permissionSelectBox
         */
        cachePermissionSelectBox: function (permissionSelectBox) {
            obj.insertSessionStorage("permission-select-box", JSON.stringify(permissionSelectBox));
        },
        getCachePermissionSelectBox: function () {
            obj.selectSessionStorage("permission-select-box");
        },
        /**
         * 把 菜单 的下拉框信息写到缓存中, 以字符串形式。以上是保存和读取操作。
         * 读取时以字符串形式返回, 使用时使用JSON.parse()方式
         * @param menuSelectBox
         */
        cacheMenuSelectBox: function (menuSelectBox) {
            obj.insertSessionStorage("menu-select-box", JSON.stringify(menuSelectBox));
        },
        getCacheMenuSelectBox: function () {
            obj.selectSessionStorage("menu-select-box");
        },
        /**
         * 缓存用户所拥有的所有菜单中的所有按钮权限, 以字符串形式保存
         * @param userMenusButtons
         */
        cacheUserMenusButtons: function (userMenusButtons) {
            obj.insertSessionStorage("user-menu-perms", JSON.stringify(userMenusButtons));
        },
        /**
         * 从缓存中取到用户所拥有的所有菜单中的所有按钮权限, 以字符串形式返回, 使用时使用JSON.parse()方式
         * @param userMenusButtons
         */
        getCacheUserMenusButtons: function () {
            obj.selectSessionStorage("user-menu-perms");
        },
        // 根据权限列表显示权限
        doShowUserPermsMenus: function() {
            var jObj = JSON.parse(sessionStorage.getItem("user-menu-perms"));
            $.each(jObj, function (index, obj) {
                //console.log(obj)
                $('.' + obj).removeClass('layui-hide')
            })
        },
        tips:function (msg, eleObj, orientation) {
            switch (orientation) {
                case 'l':
                    layer.tips(msg, eleObj, {tips: 4, time: obj.time})
                    break;
                case 'u':
                    layer.tips(msg, eleObj, {tips: 1,time: obj.time})
                    break;
                case 'd':
                    layer.tips(msg, eleObj, {tips: 3,time: obj.time})
                    break;
                default:
                    layer.tips(msg, eleObj,{time: obj.time})
            }
        },
        logout:function () {
            obj.request({
                url: DO_LOGOUT,
                successCode: obj.responseCode.user.logoutSuccess
            },function (resp, stat) {
                obj.clearApplicationStorage();
                top.window.location = LOGIN_PAGE;
            })
        },
        login: function (options, successCallback) {
            var def = {
                url: DO_LOGIN, //'/login',
                where:{},
                type:'post',
                dataType: obj.jsonType.ujson,
                traditional: false,
                successCode: obj.responseCode.success,
                timeout: 30000
            };
            var options = $.extend(def, options);
            var loadingIdx;
            $.ajax({
                url: options.url,
                data: options.where,
                type: options.type,
                dataType: options.dataType,
                traditional: options.traditional,
                success : function (resp, stat) {
                    layer.close(loadingIdx);
                    if(resp.code == options.successCode) {
                        if(successCallback) {
                            successCallback(resp, stat);
                        }
                    }else{
                        obj.defaultErrorhandler(resp);
                    }
                },
                error: function (jqXhr, status, e) {
                    layer.close(loadingIdx);
                    layer.msg("服务器异常")
                },
                beforeSend: function () {
                    loadingIdx = layer.load(1, {
                        shade: [0.1,'#fff'] //0.1透明度的白色背景
                    });
                }
            });
        },
        toLoginPage: function(){
            top.window.location = LOGIN_PAGE;
        },
        clearApplicationStorage: function () {
            sessionStorage.removeItem("user")//清空信息
            sessionStorage.removeItem("permission-select-box")//清空信息
            sessionStorage.removeItem("menu-select-box")//清空信息
            sessionStorage.removeItem("user-menu-perms")//清空按钮权限信息

            localStorage.removeItem('userTable');
            localStorage.removeItem('menu-button-list');
        },
        clearSessionStorage: function () {
            sessionStorage.clear();
        },
        clearLocalStorage: function () {
            localStorage.clear();
        },
        insertSessionStorage: function (key, value) {
            sessionStorage.setItem(key, value);
        },
        deleteSessionStorage: function (key) {
            sessionStorage.removeItem(key);
        },
        updateSessionStorage: function (key, value) {
            sessionStorage.setItem(key, value);
        },
        selectSessionStorage: function (key) {
            return sessionStorage.getItem(key);
        },
        clearAll: function () {
            sessionStorage.clear();
        },
        /**
         * 在表格页面操作成功后弹窗提示
         * @param content
         */
        tableSuccessMsg: function (content) {
            layer.msg(content, {icon: 1, time: 1000}, function () {
                // 刷新当前页table数据
                $(".layui-laypage-btn")[0].click();
            });
        },
        /**
         * confirm()函数二次封装
         * @param content
         * @param yesFunction
         */
        confirm: function (content, yesFunction) {
            let options = {skin: obj.skinChoose(), icon: 3, title: "提示", anim: obj.animChoose()};
            layer.confirm(content, options, yesFunction);
        },
        /**
         * open()函数二次封装,支持在table页面和普通页面打开
         * @param title
         * @param content
         * @param width
         * @param height
         * @param successFunction
         * @param endFunction
         */
        open: function (title, content, width, height, successFunction, endFunction) {
            layer.open({
                title: title,
                type: 2,
                maxmin: true,
                shade: 0.5,
                anim: obj.animChoose(),
                area: [width, height],
                content: content,
                zIndex: layer.zIndex,
                skin: obj.skinChoose(),
                success: successFunction,
                end: endFunction
            });
        },
        /**
         * msg()函数二次封装
         */
        // msg弹窗默认消失时间
        time: 1000,
        // 绿色勾
        greenTickMsg: function (content, callbackFunction) {
            let options = {icon: 1, time: obj.time, anim: obj.animChoose()};
            layer.msg(content, options, callbackFunction);
        },
        // 红色叉
        redCrossMsg: function (content, callbackFunction) {
            let options = {icon: 2, time: obj.time, anim: obj.animChoose()};
            layer.msg(content, options, callbackFunction);
        },
        // 黄色问号
        yellowQuestionMsg: function (content, callbackFunction) {
            let options = {icon: 3, time: obj.time, anim: obj.animChoose()};
            layer.msg(content, options, callbackFunction);
        },
        // 灰色锁
        grayLockMsg: function (content, callbackFunction) {
            let options = {icon: 4, time: obj.time, anim: obj.animChoose()};
            layer.msg(content, options, callbackFunction);
        },
        // 红色哭脸
        redCryMsg: function (content, callbackFunction) {
            let options = {icon: 5, time: obj.time, anim: obj.animChoose()};
            layer.msg(content, options, callbackFunction);
        },
        // 绿色笑脸
        greenLaughMsg: function (content, callbackFunction) {
            let options = {icon: 6, time: obj.time, anim: obj.animChoose()};
            layer.msg(content, options, callbackFunction);
        },
        // 黄色感叹号
        yellowSighMsg: function (content, callbackFunction) {
            let options = {icon: 7, time: obj.time, anim: obj.animChoose()};
            layer.msg(content, options, callbackFunction);
        },
        /**
         * 皮肤选择
         * @returns {string}
         */
        skinChoose: function () {
            let storage = window.localStorage;
            let skin = storage.getItem("skin");
            if (skin == 1) {
                // 灰白色
                return "";
            } else if (skin == 2) {
                // 墨绿色
                return "layui-layer-molv";
            } else if (skin == 3) {
                // 蓝色
                return "layui-layer-lan";
            } else if (!skin || skin == 4) {
                // 随机颜色
                var skinArray = ["", "layui-layer-molv", "layui-layer-lan"];
                return skinArray[Math.floor(Math.random() * skinArray.length)];
            }
        },
        /**
         * 动画选择
         * @returns {number}
         */
        animChoose: function () {
            let storage = window.localStorage;
            let anim = storage.getItem("anim");
            let animArray = ["0", "1", "2", "3", "4", "5", "6"];
            if (animArray.indexOf(anim) > -1) {
                // 用户选择的动画
                return anim;
            } else if (!anim || anim == 7) {
                // 随机动画
                return Math.floor(Math.random() * animArray.length);
            }
        },
        // layui table.js 操作
        /**
         * 主要用于针对表格批量操作操作之前的检查
         * @param table
         * @returns {string}
         */
        tableBatchCheck: function (table) {
            var checkStatus = table.checkStatus("tableId");
            var rows = checkStatus.data.length;
            if (rows > 0) {
                var idsStr = "";
                for (var i = 0; i < checkStatus.data.length; i++) {
                    idsStr += checkStatus.data[i].id + ",";
                }
                return idsStr;
            } else {
                layer.msg("未选择有效数据", {offset: "t", anim: 6});
            }
        },
        /**
         * https://www.cnblogs.com/lyggqm/p/5691480.html
         * DOM方法：
         * 父窗口操作IFRAME：window.frames["iframeSon"].document   或者如 B-iframe调用A-iframe的方法，  parent.A-iframe的ID号iframeSon.方法()
         * IFRAME操作父窗口: window.parent.document
         *
         * jquery方法:
         * 在父窗口中操作 选中IFRAME中的所有输入框：(window.frames["iframeSon"].document).find(”:text”);
         * 在IFRAME中操作选中父窗口中的所有输入框：(window.parent.document).find(”:text”);
         *
         * iframe框架的HTML：<iframe src=”test.html” id=”iframeSon” width=”700″ height=”300″ frameborder=”0″ scrolling=”auto”></iframe>
         * 原理其实很简单，就是用到了$(DOM对象)转换成jquery对象。
         *
         * 在子iframe页面上获取到从主页面传递的 URL 后的请求参数，子iframe中使用，因为使用子iframe中window对象
         * 122.html?param1=value1&param2=value2...
         * @param paramKey
         */
        getHTMLQueryParamValByKey(paramKey) {
            var paramsStr = window.location.search.substring(1);
            var keyValuePairStrs = paramsStr.split('&');
            for(var i = 0; i < keyValuePairStrs.length; i++){
                var nvPairStr = keyValuePairStrs[i].split('=');
                if(paramKey === nvPairStr[0]) {
                    return nvPairStr[1];
                }
                return '';
            }
        },
        getHTMLQueryParamValByParamKey(paramKey) {//方法同上
            var reg = new RegExp("(^|&)" + paramKey + "=([^&]*)(&|$)", "i");
            var url = window.location.search;//得到query部分 ?param1=value1&param2=value2...
            // url.substr(1) = param1=value1&param2=value2...
            var r = url.substr(1).match(reg);
            //console.log(r);//Array(4) [ "id=1001", "", "1001", "" ]
            if (r != null) return r[2];
            return '';
        },

        regEmail: function(value) {
            //var reg = new RegExp("^(\w+((-\w+)|(\.\w+))*)\+\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$");
            var reg = new RegExp("(^$)|(^[a-zA-Z0-9]+[-|a-z0-9A-Z._]+@([a-zA-Z0-9]+(-[a-zA-Z0-9]+)?\\.)+[a-z]{2,}$)");
            //if(value != '' && value.length > 0){//有输入内容方进行校验
                if(!reg.test(value)){
                    return '电子邮件格式不正确';
                }
            //}
        },
        regMobile: function(value){
            if(!/(^$)|(^1\d{10}$)/.test(value)){
                return '手机号码格式不正确';
            }
        },



    };

    exports('api', obj)
})